<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Models\Project;
use App\Models\Resource;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;
use Qcloud\Cos\Client;

class UploadFileController extends Controller
{
    protected $cosClient;

    public function __construct()
    {
        // 初始化COS客户端
        $this->cosClient = new Client([
            'region' => 'ap-shanghai',
            'schema' => 'https',
            'credentials' => [
                'secretId' => env('UPLOAD_APP_ID'),
                'secretKey' => env('UPLOAD_APP_KEY'),
            ]
        ]);
    }

    public function video(Request $request){
        $secret_id = env('UPLOAD_APP_ID');
        $secret_key = env('UPLOAD_APP_KEY');
        // 确定签名的当前时间和失效时间
        $current = time();
        $expired = $current + 86400;  // 签名有效期：1天
        // 向参数列表填入参数
        $arg_list = array(
            "secretId" => $secret_id,
            "currentTimeStamp" => $current,
            "expireTime" => $expired,
            "random" => rand()
        );
        // 计算签名
        $original = http_build_query($arg_list);
        $signature = base64_encode(hash_hmac('SHA1', $original, $secret_key, true).$original);
        return response()->json([
            'code' => 200,
            'data' => $signature
        ]);
    }

    public function upload(Request $request)
    {
        // 验证请求
        $validator = Validator::make($request->all(), [
            'files' => 'required|file|max:10240', // 最大10MB
        ]);

        if ($validator->fails()) {
            return response()->json([
                'code' => 500,
                'message' => '验证失败',
                'errors' => $validator->errors()
            ], 400);
        }

        // 获取上传的文件
        $files = $request->file('files');

        // 生成唯一文件名
        $fileName = time() . '_' . $files->getClientOriginalName();

        // 构建存储路径（带可选文件夹）
        $folder = $request->input('folder', '');
        $cosPath = !empty($folder) ? "{$folder}/{$fileName}" : $fileName;

        // 临时文件路径
        $localFilePath = $files->getPathname();

        try {
            // 上传到COS
            $result = $this->cosClient->putObject([
                'Bucket' => env('UPLOAD_APP_BUCKET'),
                'Key' => $cosPath,
                'Body' => fopen($localFilePath, 'r'),
                'ACL' => 'public-read', // 公共读权限
            ]);

            // 构建访问URL
            $fileUrl = $this->buildFileUrl($cosPath);

            //上传的文件存入文件库
            $resource = new Resource();
            $resource->company_id = $request->company_id;
            $resource->project_id = $request->project_id ?? 0;
            $resource->original_name = $files->getClientOriginalName();
            $resource->name = $fileName;
            $resource->path = $cosPath;
            $resource->size = $files->getSize();
            $resource->url = env('UPLOAD_APP_PREFIX').$cosPath;
            $resource->save();

            return response()->json([
                'code' => 200,
                'message' => '上传成功',
                'data' => $resource,
            ]);

        } catch (\Exception $e) {
            Log::error('COS上传失败: ' . $e->getMessage());

            return response()->json([
                'code' => 500,
                'message' => '上传失败: ' . $e->getMessage()
            ], 500);
        } finally {
            // 确保临时文件被删除
            if (file_exists($localFilePath)) {
                unlink($localFilePath);
            }
        }
    }

    public function frontend(Request $request)
    {
        // 验证请求
        $validator = Validator::make($request->all(), [
            'files' => 'required|file|max:10240', // 最大10MB
            'project_id' => 'required',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'code' => 500,
                'message' => '验证失败',
                'errors' => $validator->errors()
            ], 400);
        }

        $project = Project::where('id',$request->project_id)->first();
        if(!$project){
            return response()->json([ 'code' => 500, 'message' => '项目不存在'], 500);
        }
        // 获取上传的文件
        $files = $request->file('files');

        $fileInfo = pathinfo($files->getClientOriginalName());
        // 返回后缀名（如果存在），否则返回空字符串
        $fileInfo['extension'] = isset($fileInfo['extension']) ? strtolower($fileInfo['extension']) : '';

        // 生成唯一文件名
        $fileName = time() . '_' . $this->getRandomNumberString(12).'.'.$fileInfo['extension'];

        // 构建存储路径（带可选文件夹）
        $folder = $request->input('folder', '');
        $cosPath = !empty($folder) ? "{$folder}/{$fileName}" : $fileName;

        // 临时文件路径
        $localFilePath = $files->getPathname();

        try {
            // 上传到COS
            $result = $this->cosClient->putObject([
                'Bucket' => env('UPLOAD_APP_BUCKET'),
                'Key' => $cosPath,
                'Body' => fopen($localFilePath, 'r'),
                'ACL' => 'public-read', // 公共读权限
            ]);

            // 构建访问URL
            $fileUrl = $this->buildFileUrl($cosPath);

            //上传的文件存入文件库
            $resource = new Resource();
            $resource->company_id = $project->company_id;
            $resource->project_id = $request->project_id ?? 0;
            $resource->original_name = $files->getClientOriginalName();
            $resource->name = $fileName;
            $resource->path = $cosPath;
            $resource->size = $files->getSize();
            $resource->url = env('UPLOAD_APP_PREFIX').$cosPath;
            $resource->save();

            return response()->json([
                'code' => 200,
                'message' => '上传成功',
                'data' => $resource,
            ]);

        } catch (\Exception $e) {
            Log::error('COS上传失败: ' . $e->getMessage());

            return response()->json([
                'code' => 500,
                'message' => '上传失败: ' . $e->getMessage()
            ], 500);
        } finally {
            // 确保临时文件被删除
            if (file_exists($localFilePath)) {
                unlink($localFilePath);
            }
        }
    }

    /**
     * 3. 生成指定长度的随机数字字符串
     * @param int $length 长度
     * @return string 随机数字字符串
     */
    function getRandomNumberString($length = 12) {
        $result = '';
        // 第一位避免为0
        $result .= mt_rand(1, 9);

        // 生成剩余位数
        for ($i = 1; $i < $length; $i++) {
            $result .= mt_rand(0, 9);
        }
        return $result;
    }

    /**
     * 构建文件访问URL
     */
    private function buildFileUrl($cosPath)
    {
        $cdnDomain = env('COS_CDN_DOMAIN');
        $bucket = env('COS_BUCKET');
        $region = env('COS_REGION');

        if ($cdnDomain) {
            // 使用CDN域名
            return "https://{$cdnDomain}/{$cosPath}";
        } else {
            // 使用默认域名
            return "https://{$bucket}.cos.{$region}.myqcloud.com/{$cosPath}";
        }
    }
}
